package com.scau.service.impl;

import com.scau.common.exception.BusinessException;
import com.scau.dao.AdminDao;
import com.scau.entity.Admin;
import com.scau.entity.Counselor;
import com.scau.service.AdminService;
import com.scau.util.BeanUtil;
import com.scau.util.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.transaction.Transactional;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminDao adminDao;

    private Logger logger = LoggerFactory.getLogger(AdminService.class);

    @Transactional
    @Override
    public void save(Admin admin) {
        try {
            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
            Admin cache = adminDao.save(admin);
            BeanUtils.copyProperties(cache, admin);
        } catch (DataIntegrityViolationException e) {
            logger.error("用户账号账号已存在", e);
            throw new BusinessException("用户账号账号已存在");
        }
    }

    @Override
    public void login(String address, Admin admin) {

        Admin account = adminDao.findByAccountAndPassword(admin.getAccount(),DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));

        if (account == null) {
            throw new BusinessException("账号或者密码错误");
        } else {
            SessionUtil.putAdmin(address, account);
        }
    }

    @Override
    public Admin update(Admin newAdmin) {
        if (newAdmin.getPassword() != null) {
            newAdmin.setPassword(DigestUtils.md5DigestAsHex(newAdmin.getPassword().getBytes()));
        }
        Admin existing = adminDao.findOne(newAdmin.getId());
        BeanUtil.copyNonNullProperties(newAdmin, existing);
        adminDao.save(existing);
        return existing;
    }
}
